package com.freewater.javabase.demo.network.post;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

public class FormPoster {

    private URL url;
    private QueryString queryString = new QueryString();

    public FormPoster(URL url) {
        this.url = url;
    }

    public URL getUrl() {
        return url;
    }

    public QueryString getQueryString() {
        return queryString;
    }

    public void addParam(String name, String value) {
        this.queryString.add(name, value);
    }

    public InputStream post() throws IOException {
        final URLConnection urlConnection = url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 11; Windows NT 5.1)");
        // 必须要关闭流，否则不会发送任何数据
        try (final OutputStream outputStream = urlConnection.getOutputStream();
             final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
             final OutputStreamWriter writer = new OutputStreamWriter(bufferedOutputStream, Charset.forName("utf-8"))) {
            writer.write(queryString.toString());
        }
        return urlConnection.getInputStream();
    }
}
